package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.wemedia.WemediaContans;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmNewsDto;
import com.heima.model.wemedia.dto.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.controller.v1.WmNewsController;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.omg.CORBA.WCharSeqHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xiaosiqi
 * @date 2021/8/9 22:40
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${fdfs.url}")
    private String fileServerUrl;

    /**
     * 按条件查询自媒体文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult find(WmNewsPageReqDto dto) {
        //1.参数检查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();
        //2.分页条件查询
        IPage<WmNews> pageParam = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //查询当前登录用户的信息
        WmUser user = WmThreadLocalUtils.getUser();
        lambdaQueryWrapper.eq(WmNews::getUserId, user.getApUserId());
        //状态精确查询
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //频道精确查询
        if (null != dto.getChannelId()) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }

        //时间范围查询
        if (dto.getBeginPubdate() != null && dto.getEndPubdate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubdate(), dto.getEndPubdate());
        }

        //关键字模糊查询
        if (null != dto.getKeyWord()) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyWord());
        }

        //按照创建日期倒序
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        IPage<WmNews> pageResult = page(pageParam, lambdaQueryWrapper);
        //3.结果封装返回
        PageResponseResult<List<WmNews>> responseResult = new PageResponseResult<>(dto.getPage(), dto.getSize(), (int) pageResult.getTotal());
        responseResult.setData(pageResult.getRecords());
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    /**
     * 自媒体文章发布
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult summitNews(WmNewsDto dto) {
        //1.检查参数
        if (dto == null || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //前端传过来的状态必须是草稿或者提交
        if (!(dto.getStatus() == WmNews.Status.SUBMIT.getCode() || (dto.getStatus() == WmNews.Status.NORMAL.getCode()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = new WmNews();
        copyProperties(dto, wmNews);
        submitWmNews(dto, wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 根据文章id查询文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1.参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        //2.查询数据
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        //3.结果返回
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        //3.判断当前文章的状态  status==9  enable == 1
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable().equals(WemediaContans.WM_NEWS_ENABLE_UP)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }

        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);


    }

    /**
     * 封装基本数据
     */
    private void copyProperties(WmNewsDto dto, WmNews wmNews) {
        WmUser user = WmThreadLocalUtils.getUser();
        wmNews.setId(dto.getId());
        //设置自媒体用户ID
        wmNews.setUserId(user.getApUserId());
        //设置文章标题
        wmNews.setTitle(dto.getTitle());
        //设置标签
        wmNews.setLabels(dto.getLabels());
        //设置图文内容
        wmNews.setContent(dto.getContent());
        //设置文章状态
        wmNews.setStatus(dto.getStatus());
        //设置文章布局
        wmNews.setType(dto.getType());
        //设置图文频道ID
        wmNews.setChannelId(dto.getChannelId());
        //设置定时发布时间
        wmNews.setPublishTime(dto.getPublishTime());
        if (dto.getPublishTime()==null){
            wmNews.setPublishTime(new Date());
        }
        //设置作者Id
        wmNews.setArticleId(null);
        //设置创建时间
        wmNews.setCreatedTime(new Date());
        //设置提交时间
        wmNews.setSubmitedTime(new Date());
    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    /**
     * 提交文章
     *
     * @param dto
     */
    private void submitWmNews(WmNewsDto dto, WmNews wmNews) {
        //保存或修改文章
        if (dto.getId() == null) {
            save(wmNews);
        } else {
            //如果是修改，应先删除素材与文章的关系
            LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WmNewsMaterial::getNewsId, wmNews.getId());
            wmNewsMaterialMapper.delete(queryWrapper);
            if (wmNews.getType()==-1){
                wmNews.setType(null);
            }
            updateById(wmNews);
        }
        //关联图片关系
        images(dto, wmNews);
        kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC,JSON.toJSONString(wmNews.getId()));
    }


    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    /**
     * 设置封面图片
     */
    private void images(WmNewsDto dto, WmNews wmNews) {
        //取出文章图片
        String content = dto.getContent();
        List<Map> maps = JSON.parseArray(content, Map.class);
        List<String> imgURIs = new ArrayList<>();
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                String imgUrl = (String) map.get("value");
                imgUrl = imgUrl.replace(fileServerUrl, "");
                imgURIs.add(imgUrl);
            }
        }
        List<String> images = dto.getImages();
        List<String> images2 = new ArrayList<>();
        for (String image : images) {
            images2.add(image.replace(fileServerUrl, ""));
        }
        dto.setImages(images2);
        //自动计算封面图片
        if (WemediaContans.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            //内容中的图片数量小于等于2  设置为单图
            if (imgURIs.size() > 0 && imgURIs.size() <= 2) {
                wmNews.setType(WemediaContans.WM_NEWS_SINGLE_IMAGE);
                dto.setImages(Collections.singletonList(imgURIs.get(0)));
            } else if (imgURIs.size() > 2) {
                dto.setImages(imgURIs.stream().limit(3).collect(Collectors.toList()));
                wmNews.setType(WemediaContans.WM_NEWS_MANY_IMAGE);
            } else {
                //内容中没有图片，则是无图
                dto.setImages(new ArrayList<>());
                wmNews.setType(WemediaContans.WM_NEWS_NONE_IMAGE);
            }
        }
        //提交时关联素材和内容的关系
        if (dto.getStatus() == WmNews.Status.SUBMIT.getCode()) {
            //关联内容图片
            saveRelativeInfoForContent(imgURIs, wmNews, (short) 0);
            //关联封面图片
            saveRelativeInfoForContent(dto.getImages(), wmNews, (short) 1);
        }
        //取出封面图片
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            wmNews.setImages(dto.getImages().toString().replace("[", "")
                    .replace("]", "").replace(fileServerUrl, "")
                    .replace(" ", ""));
        }
        updateById(wmNews);
    }

    private void saveRelativeInfoForContent(List<String> imgURIs, WmNews wmNews, Short type) {
        if (imgURIs.size() > 0) {
            LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(WmMaterial::getUrl, imgURIs);
            wrapper.eq(WmMaterial::getUserId, wmNews.getUserId());
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(wrapper);
            List<String> wmNewsMaterials = new ArrayList<>();
            for (WmMaterial wmMaterial : wmMaterials) {
                wmNewsMaterials.add(wmMaterial.getId().toString());
            }
            System.out.println(wmNewsMaterials);
            wmNewsMaterialMapper.saveRelationsByContent(wmNewsMaterials, wmNews.getId(), type);
        }
    }
}
